//
//  ClubIntegralDetailView.swift
//  77Club
//
//  Created by Apple on 2024/9/11.
//

import UIKit
import WebKit
import SwiftEntryKit

class ClubIntegralDetailCell: UITableViewCell {
    
    private let backButton = c_make_ex(UIButton.self)
        .image("Common_whiteBack").end()
    private let topImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.white).font(18.font_semiBold).alignment(.center).end()
    private let leftNumberLabel = c_make_ex(UILabel.self)
        .color(.white).font(12.font_semiBold).alignment(.center)
        .corner(6).border(.white, width: 1).end()
    private let infoLabel = c_make_ex(UILabel.self)
        .color("#1A1A1A").font(14.font_semiBold)
        .text("商品详情").end()

    var backBlock: (() -> Void)?
    
    var model: ClubMallListModel?{
        didSet{
            guard let md = model else { return }
            
            topImageView.loadImage(url: md.goods_thumb)
            nameLabel.text = md.goods_name
            leftNumberLabel.text = " 剩余库存：" + md.goods_number + "份 "
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            topImageView
            backButton
            nameLabel
            infoLabel
            leftNumberLabel
        }
        
        topImageView.leading(0).top(0).width(.screenWidth).height(375.0.Scale)
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        nameLabel.leading(15).trailing(15)
        nameLabel.Top == backButton.Bottom + 200.0.Scale
        infoLabel.leading(12.0.Scale).height(16.0.Scale).bottom(15.0.Scale)
        infoLabel.Top == topImageView.Bottom + 18.0.Scale
        leftNumberLabel.height(22.0.Scale).centerHorizontally()
        leftNumberLabel.Top == nameLabel.Bottom + 12.0.Scale
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
    }
    
    @objc private func clickBackButton(){
        
        self.backBlock?()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        topImageView.rae.corner(24, corners: [.layerMinXMaxYCorner,.layerMaxXMaxYCorner])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


class ClubIntegralDetailWebCell: UITableViewCell, WKNavigationDelegate {
    
    private let contentWebView = WKWebView()

    var updateDataBlock: ((_ model: ClubMallListModel) -> Void)?
    
    var model: ClubMallListModel?{
        didSet{
            guard let md = model else { return }
            
            if md.webHeight > 0 {
                contentWebView.heightConstraint?.constant = md.webHeight
            }
            // 将 Base64 字符串解码为 Data
            guard let decodedData = Data(base64Encoded: md.goods_desc, options: .ignoreUnknownCharacters) else { return }
            // 将 Data 转换为字符串
            let decodedString = String(data: decodedData, encoding: .utf8) ?? ""
            contentWebView.loadHTMLString(decodedString, baseURL: nil)
            
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            contentWebView
        }
        
        contentWebView.leading(0).top(0).trailing(0).bottom(0).height(200)
        
        contentWebView.isUserInteractionEnabled = false
        contentWebView.navigationDelegate = self
        contentWebView.backgroundColor = .clear
    }
    
    
    // 当页面加载完成后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // 执行 JavaScript 来计算内容的高度

        if let h = model?.webHeight, h > 0 {} else{
            webView.evaluateJavaScript("document.body.scrollHeight") { [weak self] result, error in
                if let height = result as? CGFloat {
                    // 更新 WebView 高度
                    self?.model?.webHeight = height
                    if let md = self?.model {
                        self?.updateDataBlock?(md)
                    }
                }
            }
        }

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


class ClubIntegralDetailBottomView: UIView, RaeNetworkProtocol {
    
    private let buyButton = c_make_ex(UIButton.self)
        .bgImage("Mine_integral_buy").bgImage("Mine_integral_disabuy", state: .disabled)
        .color(.white).color("#47494D", state: .disabled)
        .font(18.font_semiBold).end()
    private let collectButton = c_make_ex(UIButton.self)
        .bgImage("Mine_integral_collecte")
        .bgImage("Mine_integral_collected", state: .selected).end()
    
    var collectId: String = ""
    var buyBlock: (() -> Void)?
    
    var model: ClubMallListModel?{
        didSet{
            guard let md = model else { return }
            
            if Int(ClubUser.point) ?? 0 < Int(md.market_price) ?? 0 {
                
                buyButton.isEnabled = false
                buyButton.setImage("Mine_integral_bugCoins".toImage, for: .disabled)
                buyButton.setTitle("积分不足", for: .disabled)
            }else if Int(md.goods_number) == 0 {
                buyButton.isEnabled = false
                buyButton.setImage("Mine_integral_sellout".toImage, for: .disabled)
                buyButton.setTitle("已售罄", for: .disabled)
            }else{
                buyButton.isEnabled = true
                buyButton.setImage("Mine_integral_bugChange".toImage, for: .disabled)
                let titleStr = md.market_price + " 积分"
                buyButton.setTitle(titleStr, for: .normal)
            }
            collectButton.isSelected = md.is_shoucang == 1
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .white
        
        subviews{
            buyButton
            collectButton
        }
        
        buyButton.trailing(18.0.Scale).top(5).width(160.0.Scale).height(48.0.Scale)
        collectButton.trailing(178.0.Scale).width(88.0.Scale).height(61.0.Scale).top(0)
        
        collectButton.addTarget(self, action: #selector(clickCollectButton), for: .touchUpInside)
        buyButton.addTarget(self, action: #selector(clickBuyButton), for: .touchUpInside)
    }
    
    @objc private func clickBuyButton(){
        buyBlock?()
    }
    
    @objc private func clickCollectButton(){
        
        if collectButton.isSelected {
            Task{
                let res = await network.request(.cancelCollectGoods(goodsId: collectId, type: "1"),isShowError: false)
                if res.isSuccess {
                    collectButton.isSelected = false
                    DispatchQueue.main.async {
                        NotificationCenter.default.post(name: .updateCollectState, object: nil)
                    }
                }
            }
        }else{
            guard let goodsID = model?.goods_id else { return }
            Task{
                let res = await network.request(.collectGoods(goodsId: goodsID, type: "1"),isShowError: false)
                if res.isSuccess {
                    collectButton.isSelected = true
                    DispatchQueue.main.async {
                        NotificationCenter.default.post(name: .updateCollectState, object: nil)
                    }
                }
            }
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


class ClubIntegralBuyAlertView: UIView, RaeAnimationProtocol, RaeAnimationDelegate {
    
    func animationContainerViewSize() -> CGSize {
        CGSize(width: .screenWidth, height: 300.0.Scale)
    }
    
    func animationContainerViewStyle() -> RaeAnimationViewStyle {
        .center
    }
    
    var toBuyDetailBlock: (() -> Void)?
    
    var model: ClubMallListModel?{
        didSet{
            guard let md = model else { return }
            
            titleLabel.text = md.goods_name
            let titleString = "消耗 " + md.market_price + " 积分兑换"
            buyButton.setTitle(titleString, for: .normal)
        }
    }
    
    private let bgView = c_make_ex(UIView.self)
        .corner(12.0.Scale).bgColor(.white).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .alignment(.center).font(16.font_medium)
        .color(.black).end()
    private let exploreLabel = c_make_ex(UILabel.self)
        .alignment(.center).font(12.font_medium)
        .color(.black).text("兑换说明").end()
    private let contentLabel = c_make_ex(UILabel.self)
        .font(12.font_regular).color("#AEB0B3").line(0)
        .text("1.确认兑换，不予退还\n2.兑换成功后，平台币自动进入账号钱包中\n3.兑换的平台币可用于任何平台游戏的充值，").end()
    private let buyButton = c_make_ex(UIButton.self)
        .corner(20.0.Scale).bgColor("#E4722E")
        .font(15.font_medium).color(.white).end()
    private let cancelButton = c_make_ex(UIButton.self)
        .text("取消").color("#AEB0B3").font(13.font_medium).end()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        subviews{
            bgView.subviews{
                titleLabel
                exploreLabel
                contentLabel
                buyButton
                cancelButton
            }
        }
        
        bgView.leading(16.0.Scale).trailing(16.0.Scale).height(250.0.Scale).centerVertically()
        titleLabel.leading(16.0.Scale).trailing(16.0.Scale).top(20.0.Scale)
        exploreLabel.centerHorizontally()
        exploreLabel.Top == titleLabel.Bottom + 14.0.Scale
        contentLabel.leading(32.0.Scale).trailing(16.0.Scale)
        contentLabel.Top == exploreLabel.Bottom + 12.0.Scale
        buyButton.leading(24.0.Scale).trailing(24.0.Scale).height(40.0.Scale)
        buyButton.Top == contentLabel.Bottom + 30.0.Scale
        cancelButton.leading(24.0.Scale).trailing(24.0.Scale)
        cancelButton.Top == buyButton.Bottom + 12.0.Scale
        
        cancelButton.addTarget(self, action: #selector(clickDismissButton), for: .touchUpInside)
        buyButton.addTarget(self, action: #selector(clickBuyButton), for: .touchUpInside)
    }
    
    @objc private func clickDismissButton(){
        self.entryAnimate.animation(dismiss: self)
    }
    
    @objc private func clickBuyButton(){
        self.entryAnimate.animation(dismiss: self) {
            self.toBuyDetailBlock?()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
